package com.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.gulimall.member.dao.MemberDao;
import com.gulimall.member.entity.MemberEntity;
import com.gulimall.member.exception.PhoneExistException;
import com.gulimall.member.exception.UserNameExistException;
import com.gulimall.member.service.MemberLevelService;
import com.gulimall.member.service.MemberService;
import com.gulimall.member.utils.HttpUtils;
import com.gulimall.member.vo.MemberLoginVo;
import com.gulimall.member.vo.MemberRegistVo;
import com.gulimall.member.vo.SocialUser;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();

//        设置为普通会员
        memberEntity.setLevelId(memberLevelService.getDefaultLeval().getId());

//        检查username和moblie不重复
        this.Checkphone(vo.getPhone());
        this.CheckUsername(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());

//        设置会员密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String s = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(s);

        baseMapper.insert(memberEntity);
    }

    public void Checkphone(String phone) throws PhoneExistException{
        Integer mobile = Math.toIntExact(baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone)));
        if(mobile>0){
            throw new PhoneExistException();
        }

    }

    public void CheckUsername(String username) throws UserNameExistException{
        Integer count = Math.toIntExact(baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username)));
        if(count>0){
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {

        String loginacc = vo.getLoginacc();
        if(!StringUtils.isEmpty(loginacc)){
            String password = vo.getPassword();
            MemberEntity entity = this.getOne(new QueryWrapper<MemberEntity>().eq("mobile", loginacc).or().eq("username", loginacc).or().eq("email", loginacc));
            if(entity!=null){
                if(!StringUtils.isEmpty(password)){
                    String entityPassword = entity.getPassword();
                    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                    boolean matches = bCryptPasswordEncoder.matches(password, entityPassword);
                    if(matches){
                        return entity;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public MemberEntity login(SocialUser vo) throws Exception {

        // 根据uid判断是否使用该社交登录进行过第一次登录
        // 若登录则返回用户信息

        // 若未登录过，则将用户信息（先通过api查询到）再插入数据库
        String name="";
        Map<String,String> map=new HashMap<>();
        map.put("access_token", vo.getAccess_token());
//        请求当前用户的登录信息
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), map);
        if(response.getStatusLine().getStatusCode()==200){
            String s = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(s);
            int id = (int)jsonObject.get("id");
            name = (String)jsonObject.get("name");
            vo.setUid(id+"");
        }

        LambdaQueryWrapper<MemberEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MemberEntity::getSocialUid,vo.getUid());
        MemberEntity entity = this.getOne(lqw);

        if(entity!=null){
            //这个用户已经注册
            //Access_token存在过期时间，所以每一次登录需要更新Access_token
            MemberEntity update = new MemberEntity();
            update.setId(entity.getId());
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(Long.parseLong(vo.getExpires_in()+""));
            baseMapper.updateById(update);

            entity.setExpiresIn(Long.parseLong(vo.getExpires_in()+""));
            entity.setAccessToken(vo.getAccess_token());
            return entity;
        }else{
            //没有就注册
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(Long.parseLong(vo.getExpires_in()+""));
            memberEntity.setSocialUid(vo.getUid());
            memberEntity.setNickname(name);

            baseMapper.insert(memberEntity);
            return memberEntity;
        }
//        return  null;
    }

}